package com.example.demo006miniojavaboy.minio;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 提供一个 MinIO 文件上传工具类
 */
@Component
public class MinioUtil {
    private static final Logger logger = LoggerFactory.getLogger(MinioUtil.class);
    @Autowired
    MinioClient client;
    @Autowired
    MinioProperties minioProperties;

    /**
     * 上传文件
     */
    public UploadResponse uploadFile(MultipartFile file,String bucketName) throws Exception {
        // 1. 判断文件是否为空
        if (file == null || file.getSize() == 0){
            return null;
        }
        // 2. 判断存储桶是否存在，不存在则创建
        createBucket(bucketName);
        // 3. 获取新文件名 = uuid-原始文件名.后缀名
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString() + "-" + originalFilename;
        // 4. 开始上传
        putObject(bucketName,newFileName,file.getInputStream(),file.getContentType());
        // 5. 拼接返回路径并返回
        String minioUrl = minioProperties.getEndpoint() + "/" + bucketName + "/" + newFileName;
        String nginxUrl = minioProperties.getNginxHost() + "/" + bucketName + "/" + newFileName;
        return new UploadResponse(minioUrl,nginxUrl);
    }

    /**
     * 判断存储桶是否存在，不存在则创建
     */
    public void createBucket(String bucketName) throws Exception {
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() throws Exception {
        return client.listBuckets();
    }

    /**
     * 根据bucketName获取信息
     */
    public Optional<Bucket> getBucket(String bucketName) throws Exception {
        return client.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }

    /**
     * 根据bucketName删除信息
     */
    public void removeBucket(String bucketName) throws Exception {
        if (client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            logger.info("名为 {} 的bucket删除成功.", bucketName);
        } else {
            logger.info("名为 {} 的bucket不存在，不需要删除.", bucketName);
        }
    }

    /**
     * 获取⽂件外链
     */
    public String getObjectURL(String bucketName, String objectName) throws Exception {
        return getObjectURL(bucketName, objectName, 7, TimeUnit.DAYS);
    }

    public String getObjectURL(String bucketName, String objectName, int expiry, TimeUnit timeUnit) throws Exception {
        return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName).expiry(expiry, timeUnit).method(Method.GET).build());
    }

    /**
     * 获取文件
     */
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        return client.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 上传文件
     */
    public void putObject(String bucketName, String objectName, InputStream stream, String contentType) throws Exception {
        client.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(stream, stream.available(), -1).contentType(contentType).build());
    }

    /**
     * 获取⽂件信息
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject
     */
    public StatObjectResponse getObjectInfo(String bucketName, String objectName) throws Exception {
        return client.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 删除文件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-apireference.html#removeObject
     */
    public void removeObject(String bucketName, String objectName) throws Exception {
        if (client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        }
    }

    public Iterable<Result<Item>> listObjects(String bucketName,String prefix) throws Exception{
        return listObjects(bucketName,prefix,false);
    }
    public Iterable<Result<Item>> listObjects(String bucketName,String prefix,boolean recursive) throws Exception{
        return client.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
    }
}
